package cn.hhy.hrm.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity  //开启Security
public class SmsAuthConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

    @Autowired
    private UserDetailsService myUserDetailsService ;

    @Autowired
    private MyAuthenticationFailureHandler myAuthenticationFailureHandler;


    @Autowired
    private MyAuthenticationSuccessHandler myAuthenticationSuccessHandler;

    @Override
    public  void configure(HttpSecurity http) throws Exception {

        //短信验证码登录=========================================================================================start
        //短信认证Filter
        SmsAuthFilter smsAuthFilter = new SmsAuthFilter();
        smsAuthFilter.setAuthenticationSuccessHandler(myAuthenticationSuccessHandler);
        smsAuthFilter.setAuthenticationFailureHandler(myAuthenticationFailureHandler);

        smsAuthFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));

        //短信认证provider
        SmsDaoAuthenticationProvider smsDaoAuthenticationProvider = new SmsDaoAuthenticationProvider();
        smsDaoAuthenticationProvider.setUserDetailsService(myUserDetailsService);


        //添加短信认证provider
        http.authenticationProvider(smsDaoAuthenticationProvider);
        //添加短信认证filter
        http.addFilterAfter(smsAuthFilter, UsernamePasswordAuthenticationFilter.class);

        //短信验证码登录=========================================================================================end
    }
}